<?
include('config.php');

switch($_GET['action']) {
	
	case '_log':
		_logToPage($_GET['logText']);
	
	case 'deletePageLogger':
		$_SESSION['FF']['pageLogger'] = null;
		break;
	
	case 'setDataPerPage':
		$_CONF->setValue("CONFIG>TABLES>TABLE.name=".$_GET['table'].".dataPerPage", $_GET['num']);
		$_CONF->saveBuiltXML(true);
		unset($_SESSION['FF'][$_GET['table']]["dataPerPage"]);
		echo "CONFIG>TABLES>TABLE.name=".$_GET['table'].".dataPerPage >>>> ".$_GET['num'];
		break;
	
	case 'refreshFastEdited':
		echo "<htmlcode>";
		$_TABLE = new table($_GET['table']);
		$query = "SELECT ".$_GET['campoGet']." FROM ".$_TABLE->table." WHERE ".$_DB->getIdField($_TABLE->table)." = " . $_GET['id'];
		$res = $_DB->query($query);
//		if($res !== false) echo "<htmlcode>".$res[0][$_GET['campoGet']]."<htmlcode>";
		$_FIELD = $_CONF->get("TABLE>FIELDS>FIELD.name=".$_GET['campoGet'].".node", $_TABLE->CONF);
		if($res !== false) $_TABLE->showData($res[0][$_GET['campoGet']], (($_FIELD) ? $_FIELD : $_GET['campoGet']), $_GET['id']);
		else echo "KO";
		echo "<htmlcode>";
		break;
	
	case 'saveFastEdit':
		if($_GET['loadingType_' . $_GET['field']] == 'BROWSE') {
			$value = $_TABLE->uploadFile($name . '_filesystem');
		}
		$query = "update ".$_GET['table']." set ".$_GET['field']." = '".$_GET[$_GET['field']]."' where ".$_GET['idField']." = '".$_GET['idValue']."' ";
		$res = $_DB->query($query);
		if($res !== false) echo "OK";
		return $res;
		break;
		
	case 'removeUploadedFile': 
		$_TABLE = new table($_GET['table']);
		$uploadDir = $_CONF->get('CONFIG>ADMIN>ADMINLOADINGPATH.nodeValue');
		$dir = $_SERVER['DOCUMENT_ROOT'].$uploadDir.$_TABLE->table."/";
		
		$res = $_TABLE->removeFile($_GET['fileName'], $dir);
		if($res) echo "OK";
		else return "KO";
		break;
		
	case 'removeUser': 
		$res = $_CONF->remove('CONFIG>USERS>ACCOUNT.name='.$_GET['userName'].'.node');
		if($res !== false) {
			$_CONF->saveBuiltXML(false);
			echo "OK";
		} else echo "KO";
		break;
	
	case 'getFilterConsole':
		?><htmlcode><h2>Imposta il filtro</h2><form action="content.php?table=<?=$_GET['table']?>&action=SetFilter" method="post"><table><?
		foreach($_DB->getFields($_GET['table']) as $name => $type) {
			$_FIELD = $_CONF->get('CONFIG>TABLES>TABLE.name='.$_GET['table'].'>FIELDS>FIELD.name='.$name.'.node');
			$field_name = $_CONF->get('FIELD.title', $_FIELD);
			if(
				$_SESSION['FF']['logType'] == 2 || 
				($_CONF->get("ACCOUNT>TABLES>TABLE.name=".$_GET['table'].".node", $_SESSION['FF']['logArray']) !== false &&
				$_CONF->get('FIELD.visible', $_FIELD) != 'false')
			) {
				echo '<tr><td><strong>'.(($field_name)?$field_name:$name).'</strong></td><td>
					<select name="'.$name.'_filterType">
					<option value="eq">Uguale a</option>
					<option value="noteq">Diverso da</option>
					<option value="present">Contiene</option>
					<option value="notpresent">Non contiene</option>
					'.(($type == 'int' || $type == 'real') ? '<option value="higher">Maggiore di</option>':'').'
					'.(($type == 'int' || $type == 'real') ? '<option value="lower">Minore di</option>':'').'
					</select>
				</td><td><input type="text" name="'.$name.'_filterValue"></td><td><select name="'.$name.'_option2"><option value="--">--</option><option value="and">AND</option><option value="or">OR</option></select></td><td>
					<select name="'.$name.'_filterType2">
					<option value="eq">Uguale a</option>
					<option value="noteq">Diverso da</option>
					<option value="present">Contiene</option>
					<option value="notpresent">Non contiene</option>
					'.(($type == 'int' || $type == 'real') ? '<option value="higher">Maggiore di</option>':'').'
					'.(($type == 'int' || $type == 'real') ? '<option value="lower">Minore di</option>':'').'
					</select>
				</td><td><input type="text" name="'.$name.'_filterValue2"></td></tr>';
			}
		}
		echo '</table><input type="submit" value="Filtra!"></form><htmlcode>';
		break;
	
	case 'duplicateRows':
		$ids = explode(",", $_GET['ids']);
		$_TABLE = new table($_GET['table']);
		$fields = $_DB->getFields($_TABLE->table);
		foreach($ids as $id) {
			if($id != "") {
				//echo "<hr>ID: ".$id;
				$query = "INSERT INTO ".$_TABLE->table." VALUES (";
				$res = $_DB->query("SELECT * FROM ".$_TABLE->table." WHERE ".$_DB->getIdField($_TABLE->table)." = ".$id);
				if($res !== false) {
					foreach($fields as $name => $type) {
						//echo "<br />analizing: " . $name;
						if($name == $_DB->getIdField($_TABLE->table)) {
							$query .= "''";
						} else {
							$query .= ", '".myAddSlashes($res[0][$name])."'";
						}
					}
					$query .= ")";
				}
				$res = $_DB->query($query);
				var_dump($res);
			}
		}
		break;
	
	case 'deleteMultipleRows': 
		$ids = explode(",", $_GET['ids']);
		$_TABLE = new table($_GET['table']);
		foreach($ids as $id) {
			if($id != "") {
				$query = "DELETE FROM ".$_TABLE->table." WHERE ".$_DB->getIdField($_TABLE->table)." = '" . $id . "'";
				$res = $_DB->query($query);
				echo $res;
			}
		}
		break;
		
	case 'makeExcelDump':
		$_TABLE = new table($_GET['table']);
		$_FIELDS = $_DB->getFields($_TABLE->table);
		$excel = "<table><tr>";
		foreach($_FIELDS as $field => $type) {
			if($_TABLE->isFieldVisible($field)) $excel .= "<td><strong>".strToUpper($field)."</strong></td>";
		}
		$excel .= "</tr>";
		$datas = $_DB->query("SELECT * FROM ".$_TABLE->table);
		for($i=0; $i<count($datas); $i++) {
			$excel .= "<tr>";
			foreach($_FIELDS as $field => $type) {
				if($_TABLE->isFieldVisible($field)) $excel .= "<td>".$datas[$i][$field]."</td>";
			}
			$excel .= "</tr>";
		}
		
		$excel .= "</table>";
		$fileName = "Dump_".$_TABLE->table."_".date("Y-m-d")."_".time().".xls";
		$fc = fopen($fileName, 'w') or die("can't open file");
		fwrite($fc, $excel);
		fclose($fc);
		if(is_file("Dump_".$_TABLE->table."_".date("Y-m-d")."_".time().".xls")) {
			echo "OK <filename>".$fileName."<filename>";
			_log("EXCEL Dump: File creato correttamente ($fileName)");
		} else {
			_log("EXCEL Dump: Impossibile creare il file ($fileName)");
			echo "KO";
		}
		$nextWeek = time() + (7 * 24 * 60 * 60);
		$croneTime  = date('Y-m-d', $nextWeek);
		$_TABLE->setCrone("ExcelDumpDelete", $_TABLE->table, $croneTime, $fileName);		// Una settimana
		break;
	
	case 'makeCSVDump':
		$_TABLE = new table($_GET['table']);
		$_FIELDS = $_DB->getFields($_TABLE->table);
		$csv = "";
		foreach($_FIELDS as $field => $type) {
			if($_TABLE->isFieldVisible($field)) $csv .= strToUpper($field).",";
		}
		$csv .= "\n\r";
		$datas = $_DB->query("SELECT * FROM ".$_TABLE->table);
		for($i=0; $i<count($datas); $i++) {
			foreach($_FIELDS as $field => $type) {
				if($_TABLE->isFieldVisible($field)) $csv .= $datas[$i][$field].",";
			}
			$csv .= "\n\r";
		}
		
		$fileName = "Dump_".$_TABLE->table."_".date("Y-m-d")."_".time().".csv";
		$fc = fopen($fileName, 'w') or die("can't open file");
		fwrite($fc, $csv);
		fclose($fc);
		if(is_file("Dump_".$_TABLE->table."_".date("Y-m-d")."_".time().".csv")) {
			echo "OK <filename>".$fileName."<filename>";
			_log("CSV Dump: File creato correttamente ($fileName)");
		} else {
			_log("CSV Dump: Impossibile creare il file ($fileName)");
			echo "KO";
		}
		$nextWeek = time() + (7 * 24 * 60 * 60);
		$croneTime  = date('Y-m-d', $nextWeek);
		$_TABLE->setCrone("CSVDumpDelete", $_TABLE->table, $croneTime, $fileName);		// Una settimana
		break;
	
	case 'getPlugins':
		echo '<tr><td><input type="button" value="Remove" onclick="FF.configurator.removePlugin(this, null);" /></td><td><select name="plugin'.$_GET['index'].'_ref">';
		$handle = opendir('../plugins');
		while (($file = readdir($handle)) !== false) {
			if($file != "." && $file != "..") {
				echo '<option value="'.$file.'">'.$file.'</option>';
			}
		}
		echo '</select></td><td><input type="text" name="plugin'.$_GET['index'].'_name" /></td></tr>';
		break;
	
	
	case 'saveViewportUI':
		//echo "___".$_GET['menuCol']."___" . $_CONF->get("CONFIG>UI>VIEWPORTS>MENU.width");
		if($_CONF->setAttribute("CONFIG>UI>VIEWPORTS>MENU.sx", 'sx', $_GET['menuCol']) !== false) {
			$_CONF->saveBuiltXML(true);
			echo "OK";
		}
		else echo "KO";
		break;
	
	
	
	
	// CONFIGURATOR
	
	
	
	
	case 'removeVirtualField':
		echo '<div style="padding: 10px; " align="center"><br />Vuoi rimuovere i valori virtuali per <strong>' . $_GET['field'] . '</strong>?<br /><br />';
		$_TABLE = new table($_GET['table']);
		$_FIELD = $_CONF->get("TABLE>FIELDS>FIELD.name=" . $_GET['field'] . ".node", $_TABLE->CONF);
		$vcross = $_CONF->get("FIELD>VIRTUALCROSS.node", $_FIELD);
		echo '<br /><input type="button" value="OK" onclick="var $this = this; new Ajax.Request(\'../inc/AjaxRequests.php?action=removeVirtualField_action&table='.$_GET['table'].'&field='.$_GET['field'].'\', {onComplete: function(a){$this.parentNode.parentNode.innerHTML = a.responseText;}});" /> &nbsp; <input type="button" value="ANNULLA" onclick="Confirm_alert.fire();" />
		</div>';
		echo '</div>';
		break;
	
	case 'removeVirtualField_action':
		$result = $_CONF->remove("CONFIG>TABLES>TABLE.name=".$_GET['table'].">FIELDS>FIELD.name=".$_GET['field'].">VIRTUALCROSS");
		if($result !== false) {
			$_CONF->saveBuiltXML();
			echo "<img src=\"../i/ok.jpg\" align=\"absmiddle\" hspace=14 vspace=6>Operazione eseguita con successo!.<br /><br /><div align=\"center\"><input type=\"button\" value=\"Aggiorna\" onclick=\"document.configurator.submit();\" /></div>";
		} else {
			echo "<img src=\"../i/ko.jpg\" align=\"absmiddle\" hspace=14 vspace=6>Errori durante l'esecuzione!.<br /><br /><div align=\"center\"><input type=\"button\" value=\"Aggiorna\" onclick=\"document.configurator.submit();\" /></div>";
		}
		break;
	
	case 'removeCrossField':
		echo '<div style="padding: 10px; ">Vuoi rimuovere questo cross field<br /><br />';
		$_TABLE = new table($_GET['table']);
		$_FIELD = $_CONF->get("TABLE>FIELDS>FIELD.name=" . $_GET['field'] . ".node", $_TABLE->CONF);
		$cross = $_CONF->get("FIELD>CROSS.node", $_FIELD);
		echo '<table cellpadding="4" cellspacing="0" class="NormalDataTable"><tr><th>Tabella</th><th>Campo cross</th><th>Campo visualizzato</th></tr>
		<tr><td>'.$cross['attributes']['TABLE'].'</td><td>'.$cross['attributes']['REF'].'</td><td>'.$cross['attributes']['TITLE'].'</td></tr>
		</table><br />
		Applicato al campo <strong>"'.$_GET['field'].'"</strong> della tabella <strong>"'.$_GET['table'].'"</strong>?
		<br /><br />
		<div align="center">
		<input type="button" value="OK" onclick="var $this = this; new Ajax.Request(\'../inc/AjaxRequests.php?action=removeCrossField_action&table='.$_GET['table'].'&field='.$_GET['field'].'\', {onComplete: function(a){$this.parentNode.parentNode.innerHTML = a.responseText;}});" /> &nbsp; <input type="button" value="ANNULLA" onclick="Confirm_alert.fire();" />
		</div>';
		echo '</div>';
		break;
		
	case 'removeCrossField_action':
		$result = $_CONF->remove("CONFIG>TABLES>TABLE.name=".$_GET['table'].">FIELDS>FIELD.name=".$_GET['field'].">CROSS");
		if($result !== false) {
			$_CONF->saveBuiltXML();
			echo "<img src=\"../i/ok.jpg\" align=\"absmiddle\" hspace=14 vspace=6>Operazione eseguita con successo!.<br /><br /><div align=\"center\"><input type=\"button\" value=\"Aggiorna\" onclick=\"document.configurator.submit();\" /></div>";
		} else {
			echo "<img src=\"../i/ko.jpg\" align=\"absmiddle\" hspace=14 vspace=6>Errori durante l'esecuzione!.<br /><br /><div align=\"center\"><input type=\"button\" value=\"Aggiorna\" onclick=\"document.configurator.submit();\" /></div>";
		}
		break;
}


/* CONSOLE */

switch ($_GET['ConsoleCmd']) {

	case 'query':
		$res = $_DB->query($_GET['params']);
		print_r($res);
		break;
		
	case 'log':
		print_r($_SESSION['FF']['logger']);
		break;
	
	case 'errorlog':
		if(is_file('../errorlog.txt'))
			$logFile = '../errorlog.txt';
		else 
			$logFile = '../../errorlog.txt';
		$fc = fopen($logFile, 'r') or die("can't open file");
		while (!feof($fc))  {
			$contents .= fgets($fc) . '<br>';
		}		
		
		//$cont = fread($fc, filesize($logFile));
		print_r($contents);
		break;
		
	case 'clearerrorlog':
		if(is_file('../errorlog.txt'))
			$logFile = '../errorlog.txt';
		else 
			$logFile = '../../errorlog.txt';
		$fc = fopen($logFile, 'w') or die("can't open file");
		fwrite($fc, '');
		fclose($fp);
		echo 'Errorlog successfully cleared!';
		break;
	
	case 'clearLog':
		$_SESSION['FF']['logger'] = "";
		echo "Log cleared";
		break;
	
	case 'get':
		$res = $_CONF->get($_GET['query']);
		print_r($res);
		break;
		
	case 'setValue':
		$res = $_CONF->setValue($_GET['query'], $_GET['value']);
		if($res !== false) echo "Comando eseguito";
		else echo "Errore di esecuzione";
		print_r($res);
		break;

}

















?>